package aoi.movieweb.service;

import aoi.movieweb.exception.FileStorageException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileStorageService {

    private final Path fileStorageLocation;

    public FileStorageService(@Value("${file.upload-dir}") String uploadDir) {
        this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation); // 创建目录，如果不存在
        } catch (IOException e) {
            throw new FileStorageException("无法创建上传目录，错误: " + e.getMessage());
        }
    }


    public String storeFile(MultipartFile file) {
        // 确保文件不是空的
        if (file.isEmpty()) {
            throw new FileStorageException("上传的文件不能为空");
        }

        try {
            // 创建唯一文件名
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            // 定义文件存储路径
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            // 将文件复制到目标位置
            Files.copy(file.getInputStream(), targetLocation);

            return fileName; // 返回存储后的文件名
        } catch (IOException ex) {
            throw new FileStorageException("存储文件失败: " + ex.getMessage());
        }
    }
}
